#include "differ.h"
#include "getv.h"
#include "success.h"
#include <climits>
using namespace std;

int minFlips(){
    
    //计算差异环
    vector<int> diff = differ(getv(),getv());
    unsigned int n = diff.size();

    // 输入限制数
    unsigned int a;
    cin>>a;

    // 环形处理扩展数组
    vector<int> extended_diff = diff;
    extended_diff.insert(extended_diff.end(), diff.begin(), diff.end());

    // 让初始可能最小值为无穷大
    int min_flips = INT_MAX;

    // 优化：只需检查前a个起始位置
    for (unsigned int start = 0; start < a; ++start) {
        vector<int> flip_marks(2*n + 1, 0); // 差分标记数组
        int current_flips = 0;
        int active_flips = 0;

        // 滑动窗口处理
        for (unsigned int i = start; i < start + n; ++i) {
            active_flips ^= flip_marks[i]; // 应用当前翻转标记

            // 计算当前实际状态
            int current_state = extended_diff[i % (2*n)] ^ active_flips;

            // 需要翻转时
            if (current_state) {
                if (i + a > start + n) {
                    // 无法在剩余空间完成有效翻转
                    current_flips = INT_MAX;
                    break;
                }

                // 记录翻转操作
                current_flips++;
                flip_marks[i] ^= 1;       // 翻转开始
                flip_marks[i + a] ^= 1;   // 翻转结束
                active_flips ^= 1;        // 立即生效
            }
        }

        // 验证&更新结果(利用success函数)
        if (success(extended_diff,flip_marks,start,n)) {
            min_flips = min(min_flips, current_flips);
        }
    }

    // 收获结果(-1为异常值)
    return (min_flips == INT_MAX) ? -1 : min_flips;

}